from apps.common.base.dao import BaseDao
from apps.system.user.serializers import *
from apps.account.serializers import Token
from apps.common.extension.customException import VerifyException
from apps.system.rank.dao import RankDao
from apps.system.team.dao import TeamDao
from apps.chat.message.functions import MessageFun
from apps.account.dao import AccountDao

class UserDao(BaseDao):
    MODEL_CLASS = User
    SERI_CLASS = UserBaseSerializer


    def findAllUser(self):
        _list = UserDao().findAll().filter(role__types='user').select_related('parent', 'rank', 'role', 'team', 'identity', 'account', 'lessee')
        return _list
    def findAllUserByLessee(self, lessee):
        _list = self.findAllUser().filter(lessee=lessee)
        return _list
    
    # 新增用户
    def createUser(slef, params):
        print('新增用户', params)

        if not params.get('lessee'):
            raise VerifyException('lessee参数必填')
        if not params.get('role'):
            raise VerifyException('role参数必填')

        # 设置默认rank级别
        _rank = RankDao().findOneByGrade(0)
        if _rank:
            params['rank'] = _rank.id
        else:
            print('员工级别不存在')

        # 设置默认team级别
        _team = TeamDao().findOneByGrade(0)
        if _team:
            params['team'] = _team.id
        else:
            print('团队级别不存在')

        if not params.get('checkStatus'):
            params['checkStatus'] = 'PASS'

        data = {
            'lessee': params.get('lessee'),
            'username': params.get('username'),
            'password': params.get('password') or '',
        }
        account = AccountDao().create(data)
        params['account'] = account.id
        _user = UserDao().create(params)
        if _user:
            code = 100000 + _user.id
            if not _user.nickname:
                nickname = '用户_' + str(code)
            UserDao().update(_user.id, {'code': code, 'nickname': nickname})
            MessageFun().sendMessage(None, UserDao().findOneByObjId(_user.id), 'system', {'title': '系统通知', 'content': '鑫珑名品欢迎你您！累计消费满100成为普通会员；分享2位普通会员成为VIP会员，即可享受补贴。'})
        return _user

    def replaceToken(self, userId):

        old_token = Token.objects.filter(user_id=userId)
        old_token.delete()
        token = Token.objects.create(user_id=userId)

        return token